//
//  UNTableViewModel.swift
//  Intersection
//
//  Created by 我骑着蜗牛走天下 on 2025/3/5.
//

import RxSwift
import RxCocoa
import RxAlamofire
import UIKit

open class UNTableViewModel<T> {
    
    //表格数据序列
    public let tableData = BehaviorRelay<[T]>(value: [])
     
    ///刷新状态
    public var refreshingState = BehaviorRelay<UITableView.refreshState>(value:.none)
    
    private let headerRefreshSubject = PublishSubject<Void>()
    
    public var page = 1
    
    public var oldPage = 1
    
    /// 最大页数
    public var maxPage = 0
    
    
    /// 必须使用Controller中的 DisposeBag ，不然会导致VM无法释放
    public init(input: (
        headerRefresh: Observable<Void>,
        footerRefresh: Observable<Void>? ),
     disposeBag:DisposeBag) {
        
        // 合并外部传入的headerRefresh和内部的headerRefreshSubject
        let mergedHeaderRefresh = Observable.merge(input.headerRefresh, headerRefreshSubject)
        
        mergedHeaderRefresh.observe(on: MainScheduler.instance).flatMapLatest{ [self] _ in
            page = 1
            return loadHeaderData().asDriver { [self] error in
                //转driver阻止error向上传递headerRefresh被释放导致后续不下拉请求网络 同时处理网络失败
                page = oldPage
                refreshingState.accept(.endHeader)
                return Observable.just(tableData.value).asDriver(onErrorJustReturn: tableData.value)
            }
        }.share(replay: 1).subscribe(onNext: { [weak self] items in
            guard let self = self else { return }
            page = 1
            oldPage = page
            refreshingState.accept(.endHeader)
            if page >= maxPage {
                refreshingState.accept(.endFooterNoMore)
            }
            tableData.accept(items)
        }).disposed(by: disposeBag)
        
        guard let footerRefresh = input.footerRefresh else { return }
        
        footerRefresh.observe(on: MainScheduler.instance).flatMapLatest{ [self] _ in
            page += 1
            return loadFooterData().asDriver { [self] error in
                page = oldPage
                refreshingState.accept(.endFooter)
                return Observable.just([]).asDriver(onErrorJustReturn: [])
            }
        }.share(replay: 1).subscribe(onNext: { [weak self] items in
            guard let self = self else { return }
            //上拉成功 page + 1
            page += 1
            oldPage = page
            if page >= maxPage {
                refreshingState.accept(.endFooterNoMore)
            }else{
                refreshingState.accept(.endFooter)
            }
            tableData.accept(tableData.value + items )
        }).disposed(by: disposeBag)
        
    }
    
    /// 无感知header刷新
    public func triggerHeaderRefresh() {
        headerRefreshSubject.onNext(())
    }
    
    // MARK: - 数据加载
    
    // 在子类中调用
    open func loadHeaderData() -> Single<[T]> {
        fatalError("Subclass must implement")
    }

    open func loadFooterData() -> Single<[T]> {
        fatalError("Subclass must implement")
    }
    
}
